from blog.models import Post
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import redirect
from django.views import View
from django.views.generic import ListView


class NoticeListView(LoginRequiredMixin, ListView):
    template_name = 'notice/notice_list.html'
    context_object_name = 'notices'  # 指定上下文对象的名字

    def get_queryset(self):
        return self.request.user.notifications.unread()  # 获得未读通知列表(NotificationQuerySet对象)


class NoticeUpdateView(View):
    """更新通知状态"""

    def get(self, request):
        notice_id = request.GET.get('notice_id')
        # 更新单条通知
        if notice_id:
            post = Post.objects.get(slug=request.GET.get('post_slug'))
            request.user.notifications.get(id=notice_id).mark_as_read()
            return redirect(post)  # 重定向到文章详情页面，模型中必须实现get_absolute_url方法

        # 更新全部通知
        else:
            request.user.notifications.mark_all_as_read()
            return redirect('notice:list')
